const express = require('express')
const router = express.Router()
const users = require('../model/users')
const bcrypt = require('bcrypt')
const multer = require('multer')
const fs = require('fs')
const session = require('express-session')

router.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}))


const file = multer({ 'dest': 'upload' })

router.post('/register', async(req, res) => {
    let result = await users.findOne({ name: req.body.name });
    if (result) {
        res.status(400).json('姓名已被注册')
        return
    }
    let newUsers = new users({
            name: req.body.name,
            password: req.body.password,
            imgsrc: req.body.imgsrc
        })
        // 使用bcrypt方法进行密码封装
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUsers.password, salt, function(err, hash) {
            newUsers.password = hash;
            newUsers.save().then(registerResult => {
                req.session.status = 1
                req.session.userId = registerResult._id
                res.send({ code: 0, msg: 'success' })
            })
        })
    })
})

router.get('/', (req, res) => {
    res.send('home page')
})

router.get('/register', (req, res) => {
    res.render('register', {
        path: 'register'
    })
})

router.post('/login', (req, res) => {
    users.findOne({ name: req.body.name }).then(response => {
        if (response.password != req.body.password) {
            res.send({ code: 1, msg: '对不起，密码错误' })
            return;
        }
        // res.send({ code: 0, msg: 'success' })
        res.redirect('/');
    }).catch(err => {
        res.send({ code: 1, msg: '没有该用户' })
    })
})

router.get('/login', (req, res) => {
    if (req.session.status) {
        users.findOne({ _id: req.session.userId }).then(result => {
            let userInfo = {
                name: result.name,
                password: result.password
            }
            res.render('login', {
                path: 'login',
                userInfo
            })
        })
    }

})

router.post('/api/upload', file.single('avatar'), (req, res) => {
    let fileName = req.file.filename;
    let extendName = req.file.originalname.substr(req.file.originalname.lastIndexOf('.'))
    let newPath = `${fileName}${extendName}`
    fs.rename(`upload/${fileName}`, `upload/${newPath}`, (err, result) => {
        if (err) {
            res.status(400).json('上传失败')
            return;
        }
        let obj = { code: 0, uploadUrl: newPath };
        res.send(JSON.stringify(obj))
    })
})
module.exports = router;